package com.gtlab1207.br_security.ctrls;


import com.gtlab1207.br_security.common.Codes;
import com.gtlab1207.br_security.common.Result;
import com.gtlab1207.br_security.common.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller 基类
 */
public class BaseCtrl {

    @Value("${static.domain}")
    private String domain;

    @Value("${static.addVersionFiles}")
    private String addVersionFiles;

    private final Logger exLogger = LoggerFactory.getLogger("exLogger");

    @Autowired
    private RedisTemplate<Object, Object> redisClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 处理成功时的返回
     * @param o 返回的结果集
     * @return Result
     */
    protected Result send(Object o) {
        Result ret = new Result();
        ret.setResult(o);
        return ret;
    }

    /**
     * 非正常情况的返回
     * @param code 错误码
     * @param message 错误信息
     * @return Result
     */
    protected Result send(int code, String message) {
        Result ret = new Result();
        ret.setStatus(code, message);
        return ret;
    }

    /**
     * 特殊情况的反馈
     * @param o 结果集
     * @param code 状态码
     * @param message 状态信息
     * @return Result
     */
    protected Result send(Object o, int code, String message) {
        Result ret = new Result();
        ret.setStatus(code, message);
        ret.setResult(o);
        return ret;
    }

    /**
     * 通过ResultCoe类返回提示信息
     * @param resultCode
     * @return
     */
    protected Result send(Codes resultCode) {
        Result ret = new Result(resultCode);
        return ret;
    }

    /**
     * 通过ResultCode与data返回数据
     * @param resultCode
     * @param data
     * @return
     */
    protected Result send(Codes resultCode, Object data) {
        Result ret = new Result(resultCode);
        ret.setResult(data);
        return ret;
    }

    protected ModelAndView render(String viewName, Map<String, Object> data) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName(viewName);
        if (data == null) {
            data = new HashMap<String, Object>();
        }
        data.put("staticDomain", this.domain);
        //add versions
        for (String name : this.addVersionFiles.split(";")) {
            String versionKey = name.substring(0, name.lastIndexOf(".")).replaceAll("/", "-") + "-version";
            try {
                Resource staticFile = new ClassPathResource("static/" + name);
                data.put(versionKey, "-" + Util.getFileMD5(staticFile.getInputStream()));
            } catch (IOException e) {
                data.put(versionKey, "");
            }
        }
        mv.addAllObjects(data);
        return mv;
    }

    /**
     * 格式化表单验证信息
     * @param exception
     * @param response
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result formatValidatorMsg(BindException exception, HttpServletResponse response) {
        Result ret = new Result();
        BindingResult bindingResult = exception.getBindingResult();
        Map<String, String> map = new HashMap<>();
        List<FieldError> list = bindingResult.getFieldErrors();
        for (FieldError error : list) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        ret.setStatus(1001, "参数有误");
        ret.setResult(map);
        return ret;
    }

  /*  *//**
     * 全局异常拦截
     * @param ex
     * @return
     *//*
    @ExceptionHandler
    @ResponseBody
    public Result catchException(Exception ex) {
        Result ret = new Result();
        ret.setStatus(1005, "系统繁忙，请联系客服!");
        exLogger.error(ex.getMessage());
        return ret;
    }
*/

    /**
     * 写入数据到session
     * @param name
     * @param value
     * @param request
     */
    public void setValueToSession(String name, String value, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(60 * 30);
        session.setAttribute(name, value);
    }

    /**
     * 写入值到session
     * @param name
     * @param value
     * @param request
     */
    public void setValueToSession(String name, Object value, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute(name, value);
    }

    /**
     * session获取值
     * @param name
     * @param request
     * @return
     */
    public Object getValueFromSession(String name, HttpServletRequest request) {
        HttpSession session = request.getSession();
        return session.getAttribute(name);
    }

    /**
     * session删除值
     * @param name
     * @param request
     */
    public void removeValueFromSession(String name, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute(name);
    }




}
